/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.api.controller;

import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.app.param.PayUserParam;
import com.yami.shop.bean.enums.PayEntry;
import com.yami.shop.bean.model.UserExtension;
import com.yami.shop.bean.pay.PayInfoDto;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.enums.PayType;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.Arith;
import com.yami.shop.manager.impl.PayManager;
import com.yami.shop.security.api.model.YamiUser;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.PayInfoService;
import com.yami.shop.service.UserExtensionService;
import com.yami.shop.user.common.model.UserBalance;
import com.yami.shop.user.common.model.UserBalanceLog;
import com.yami.shop.user.common.service.UserBalanceLogService;
import com.yami.shop.user.common.service.UserBalanceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Objects;

/**
 * @author LHD on 2020/03/02.
 */
@Api(tags = "余额支付接口")
@RestController
@RequestMapping("/p/balance")
@AllArgsConstructor
public class PayBalanceController {

    /**
     * 会员信息
     */
    private final UserBalanceService userBalanceService;
    private final UserBalanceLogService userBalanceLogService;
    private final UserExtensionService userExtensionService;
    private final Snowflake snowflake;
    private final PayManager payManager;
    private final PayInfoService payInfoService;

    /**
     * 会员余额充值接口
     */
    @PostMapping("/pay")
    @ApiOperation(value = "会员余额充值", notes = "会员余额充值")
    @SneakyThrows
    public ServerResponseEntity<?> payVip(HttpServletResponse httpResponse, @RequestBody PayUserParam payCardParam) {
        YamiUser user = SecurityUtils.getUser();
        if (!user.getEnabled()) {
            // 您已被禁用，不能购买，请联系平台客服
            throw new YamiShopBindException("yami.order.pay.user.disable");
        }
        if (payCardParam.getPayType().equals(PayType.SCOREPAY.value()) || payCardParam.getPayType().equals(PayType.BALANCE.value())){
            // 请使用微信或支付宝进行支付
            throw new YamiShopBindException("yami.user.payType.error");
        }
        UserExtension userExtension = userExtensionService.getOne(new LambdaQueryWrapper<UserExtension>().eq(UserExtension::getUserId, user.getUserId()));
        UserBalance userBalance = null;
        // 自定义金额
        double balance;
        if (Objects.equals(payCardParam.getId(), -1L)) {
            balance = Arith.add(userExtension.getTotalBalance(), payCardParam.getCustomRechargeAmount());
        }
        // 购买
        else {
            userBalance = userBalanceService.getById(payCardParam.getId());
            if (Objects.isNull(userBalance)) {
                // 当前余额充值选项已被删除
                throw new YamiShopBindException("yami.user.blance.not.exist");
            }
            balance = Arith.add(userExtension.getTotalBalance(), userBalance.getRechargeAmount());
        }
        if (balance > Constant.MAX_USER_BALANCE) {
            // 您的余额加充值的余额将大于最大余额，不能进行充值操作
            throw new YamiShopBindException("yami.balance.than.max.balance");
        }
        // 使用雪花算法生成支付单号
        String payNo = String.valueOf(snowflake.nextId());
        Date now = new Date();

        //生成余额充值日志
        UserBalanceLog userBalanceLog = new UserBalanceLog();
        userBalanceLog.setCreateTime(now);
        userBalanceLog.setIoType(1);
        userBalanceLog.setType(1);
        userBalanceLog.setIsPayed(0);
        userBalanceLog.setPayNo(payNo);
        userBalanceLog.setUserId(user.getUserId());
        if (Objects.equals(payCardParam.getId(), -1L)) {
            userBalanceLog.setBalanceId(-1L);
            userBalanceLog.setChangeBalance(payCardParam.getCustomRechargeAmount());
        } else {
            userBalanceLog.setBalanceId(userBalance.getBalanceId());
            userBalanceLog.setChangeBalance(userBalance.getRechargeAmount());
        }
        userBalanceLogService.save(userBalanceLog);
        payCardParam.setNeedAmount(userBalanceLog.getChangeBalance());
        payCardParam.setPayNo(payNo);
        payCardParam.setOrderIds(userBalanceLog.getBalanceLogId());

        PayInfoDto payInfo = payInfoService.recharge(user.getUserId(), payCardParam);
        payInfo.setBizUserId(user.getBizUserId());
        payInfo.setPayType(payCardParam.getPayType());
        payInfo.setApiNoticeUrl("/notice/pay/" + PayEntry.RECHARGE.value() + "/" + payCardParam.getPayType());
        payInfo.setReturnUrl(payCardParam.getReturnUrl());

        return payManager.doPay(httpResponse, payInfo);
    }

    @GetMapping("/isPay")
    @ApiOperation(value = "获取余额充值支付信息", notes = "获取余额充值支付信息")
    public ServerResponseEntity<Integer> isPay(){
        YamiUser user = SecurityUtils.getUser();
        UserBalanceLog userBalanceLog = userBalanceLogService.getMaxCrtTimeByUserId(user.getUserId());
        return ServerResponseEntity.success(userBalanceLog.getIsPayed());
    }

}
